package hjnu.tools;

import com.mysql.jdbc.Statement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class MyPool {
    private static String URLADDRESS="jdbc:mysql://localhost:3306/user?characterEncoding=UTF-8";
    private static String USERNAME="root";
    private static String PASSWORD="123456";
    private static List<Connection> datas=new LinkedList<>();
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //连接池中存放15个连接对象
            for (int i = 0; i < 15; i++) {
                datas.add(DriverManager.getConnection(URLADDRESS,USERNAME,PASSWORD));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //提供了获取数据库链接对象和释放资源的静态方法
    public static java.sql.Connection getConnection(){
        if (datas.size()>0){
            return datas.remove(0);
        }else {
            return null;
        }
    }
    //释放资源Connection,Satement对象是必须有，而Resultset对象只有在查询时才会使用
    public static void releaseResource(Connection conn, Statement stm){
        if (conn!=null){
            datas.add(conn);
        }
        if (stm!=null){
            try {
                stm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            stm=null;
        }
    }
    public static void releaseResource(Connection conn, Statement stm, ResultSet rs){
        releaseResource(conn, stm);
        if (rs!=null){
            try {
                rs.close();
                rs=null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Connection conn=null;
        conn=MyPool.getConnection();
        System.out.println("first="+MyPool.datas.size());
        MyPool.releaseResource(conn,null);
        System.out.println("second="+MyPool.datas.size());
    }
}
